from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

from .. models import Types,Goods

from django.contrib.auth.decorators import permission_required


def GetTypesAll(request):

    # 模型提供 extra
    #  select *,concat(path,id) as paths from myadmin_types order by paths;
    obs = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')

    # 判断是否有搜索条件
    if request.GET.get('type',None):
        obs = obs.filter(name__contains=request.GET['keywords'])

    # 循环处理父类名,缩进
    for x in obs:
        if x.pid != 0:
            ob = Types.objects.get(id=x.pid)
            x.pname = ob.name

    return obs


# 分类列表
@permission_required('myadmin.show_types',raise_exception=True)
def index(request):
    # 获取数据
    obs = GetTypesAll(request)

    # 数据分页
    # 获取当前页的页数
    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(obs, 10)

    # 获取当前页的 数据
    userlist = p.page(pageindex)

    # 分配数据
    context = {'typelist':userlist}

    # 加载模板
    return render(request,'admin/types/index.html',context)

# 分类添加页面
@permission_required('myadmin.insert_types',raise_exception=True)

def add(request):

    # 分配数据
    context = {'typelist':GetTypesAll(request)}

    # 加载模板
    return render(request,'admin/types/add.html',context)

# 执行分类添加
@permission_required('myadmin.insert_types',raise_exception=True)
def insert(request):

    # 获取数据
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']

    # 判断当前添加的分类是否为顶级分类
    if data['pid'] == '0':
        # 顶级分类
        data['path'] = '0,'
    else:
        # 不是顶级分类
        # 先获取父级的path
        ob = Types.objects.get(id=data['pid'])
        data['path'] = ob.path+data['pid']+','
        

    # 执行添加
    ob = Types.objects.create(**data)

    if ob:
        return HttpResponse('<script>alert("分类添加成功");location.href="/myadmin/types/index/"</script>')
    else:
        return HttpResponse('<script>alert("分类添加失败");history.back(-1)"</script>')


# 执行分类删除
@permission_required('myadmin.del_types',raise_exception=True)

def delete(request):

    # 获取参数
    tid = request.GET['id']

    #  统计当前类下是否有子类
    num = Types.objects.filter(pid=tid).count()
    if num:
        return JsonResponse({'code':1,'msg':'当前类下还有子类,不能删除'}) 

    # 判断当前类下是否有商品
    num = Goods.objects.filter(tid=tid).count()
    if num:
        return JsonResponse({'code':2,'msg':'当前类下还有商品,不能删除'})

    # 可以执行删除
    ob = Types.objects.get(id=tid)
    res = ob.delete()

    if res:
        return JsonResponse({'code':0,'msg':'删除成功'})
    else:
        return JsonResponse({'code':3,'msg':'删除失败'})



# 执行分类的更新
@permission_required('myadmin.edit_types',raise_exception=True)

def update(request):
    # 获取分类名,和id
    tid = request.GET.get('id')
    name = request.GET.get('name')

    try:
        # 执行更新
        ob = Types.objects.get(id=tid)
        ob.name = name
        ob.save()
        return JsonResponse({'code':0,'msg':'修改成功'})
    except:
        return JsonResponse({'code':1,'msg':'修改失败'})
